package jsyf.oa.service.crm;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.crm.EquipmentModelDao;
import jsyf.oa.dao.crm.ExhibitionCustomerInfoDao;
import jsyf.oa.dao.crm.ExhibitionDao;
import jsyf.oa.dao.crm.ExhibitionIntentionDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wreport.WReportCusVisitDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.entity.crm.ExhibitionCustomerInfoEntity;
import jsyf.oa.entity.crm.ExhibitionIntentionEntity;
import jsyf.oa.entity.wreport.WReportCusVisitEntity;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import jsyf.oa.facade.crm.ExhibitionCustomerInfoFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wangmin on 2017/12/27.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ExhibitionCustomerInfoService implements ExhibitionCustomerInfoFacade {

    @Autowired
    private ExhibitionCustomerInfoDao exhibitionCustomerInfoDao;
    @Autowired
    ExhibitionIntentionDao exhibitionIntentionDao;
    @Autowired
    private WReportCustomerDao wReportCustomerDao;
    @Autowired
    private EquipmentModelDao equipmentModelDao;
    @Autowired
    private WReportCusVisitDao wReportCusVisitDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ExhibitionDao exhibitionDao;

    @Override
    public String save(String jsonData) {
        ExhibitionCustomerInfoEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), ExhibitionCustomerInfoEntity.class);
        String intentionModelName = "";
        String customerId = entity.getCustomerId();
        //客户信息
        WReportCustomerEntity wReportCustomerEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportCustomerEntity.class);
        wReportCustomerEntity.setName(entity.getCustomerName());
        wReportCustomerEntity.setTel(entity.getCustomerTel());
        //意向机型
        for (int i = 0; i < entity.getIntentionModelList().size(); i++) {
            ExhibitionIntentionEntity exihibitionIntentionEntity = entity.getIntentionModelList().get(i);
            if (!exihibitionIntentionEntity.getEqipmentModelId().equals("")) {
                intentionModelName += equipmentModelDao.getJSONById(exihibitionIntentionEntity.getEqipmentModelId()).get("name").toString() + "/";
            }
        }
        intentionModelName = intentionModelName.length() > 1 ? intentionModelName.substring(0, intentionModelName.length() - 1) : intentionModelName;
        wReportCustomerEntity.setIntentionModel(intentionModelName);
        //判断根据客户电话查询客户是否存在
        WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(entity.getCustomerTel());
        //添加展会客户
        if (oldWReportCustomerEntity == null) {
            //添加基础客户信息
            wReportCustomerDao.add(wReportCustomerEntity);
            customerId = wReportCustomerEntity.getId();
        }else{
            customerId = oldWReportCustomerEntity.getId();
        }
        entity.setCustomerId(customerId);
        if (entity.getId().equals("") || entity.getId().equals("0")) {
            //添加展会客户信息
            exhibitionCustomerInfoDao.add(entity);
        } else {
            wReportCustomerDao.update(wReportCustomerEntity);
            //修改展会客户信息
            exhibitionCustomerInfoDao.update(entity);
            //删除展会意向机型
            StringBuffer condition = new StringBuffer();
            String[] sqlArgs = new String[1];
            if (!StringUtils.isEmpty(entity.getId())) {
                condition.append(" AND EXHIBITION_INFO_ID=? ");
                sqlArgs[0] = entity.getId();
            }
            exhibitionIntentionDao.removeByCondition(condition.toString(), sqlArgs);
        }

        //意向机型
        for (int i = 0; i < entity.getIntentionModelList().size(); i++) {
            ExhibitionIntentionEntity exihibitionIntentionEntity = entity.getIntentionModelList().get(i);
            exihibitionIntentionEntity.setExhibitionInfoId(entity.getId());
            exhibitionIntentionDao.add(exihibitionIntentionEntity);
        }

        return entity.getId();
    }

    public JSONObject getExhibitionCustomerInfo(Integer pageIndex, String userId, String exhibitionId, String key, Boolean isExport) {
        JSONObject jsonUser = userDao.getViewJSONById(userId);
        Boolean isAllRegion = false;
        if (jsonUser != null && jsonUser.get("companyId").equals("201712161613432EAF27DBCCB7D0E6CA") || isExport)
            isAllRegion = true;
        Boolean isSupport = false;
        if (jsonUser != null && ("区域支持,大区经理,大客户总监,销售管理经理".indexOf(jsonUser.get("roleName").toString()) > -1)) {
            isSupport = true;
        }

        List<JSONObject> jsonObjectList = exhibitionCustomerInfoDao.getExihibitionCustomerInfo(pageIndex, userId, exhibitionId, key, isSupport, isExport, isAllRegion);
        Integer cusCount = exhibitionCustomerInfoDao.getExihibitionCustomerInfoCount(userId, exhibitionId, key, isSupport, isAllRegion);
        Map<String, JSONObject> jsonObjectMap = exhibitionCustomerInfoDao.getExhibitionIntentionMap(exhibitionId);
        Map<String, JSONObject> rsMap = exhibitionCustomerInfoDao.getRegion2Support();
        Map<String, JSONObject> trackMap = exhibitionCustomerInfoDao.getTrackMap(exhibitionId);
        for (JSONObject jsonObject : jsonObjectList) {
            String id = jsonObject.get("ID").toString();
//            String trackTime = jsonObject.get("TRACK_TIME").toString();
            String arrivalsTime = jsonObject.get("ARRIVALS_TIME").toString();
            String depositStatus = jsonObject.get("DEPOSIT_STATUS").toString();
            String travelModel = jsonObject.get("TRAVEL_MODEL").toString();
            String trackStatus = jsonObject.get("TRACK_STATUS").toString();
            String regionId = jsonObject.get("regionId").toString();
            String customerId = jsonObject.get("CUSTOMER_ID").toString();

            if (depositStatus.equals("1"))
                jsonObject.put("depositStatusName", "已交");
            else if (depositStatus.equals("2"))
                jsonObject.put("depositStatusName", "肯定交");
            else if (depositStatus.equals("3"))
                jsonObject.put("depositStatusName", "不确定");
            else if (depositStatus.equals("4"))
                jsonObject.put("depositStatusName", "不交");
            else
                jsonObject.put("depositStatusName", "");

            if (travelModel.equals("1"))
                jsonObject.put("travelModelName", "飞机");
            else if (travelModel.equals("2"))
                jsonObject.put("travelModelName", "火车");
            else if (travelModel.equals("3"))
                jsonObject.put("travelModelName", "自驾");
            else
                jsonObject.put("travelModelName", "");

            if (trackStatus.equals("1"))
                jsonObject.put("trackStatusName", "跟踪中");
            else if (trackStatus.equals("2"))
                jsonObject.put("trackStatusName", "放弃");
            else
                jsonObject.put("trackStatusName", "");

//            jsonObject.put("TRACK_TIME", DateUtils.parse(trackTime, "MM/dd"));
            jsonObject.put("ARRIVALS_TIME", DateUtils.parse(arrivalsTime, "MM/dd"));

            if (jsonObjectMap.containsKey(id)) {
                JSONObject object = jsonObjectMap.get(id);

                jsonObject.put("modelName", object.get("modelName"));
                jsonObject.put("quote", object.get("QUOTE"));
                jsonObject.put("acceptPrice", object.get("ACCEPT_PRICE"));
            } else {
                jsonObject.put("modelName", "");
                jsonObject.put("quote", "");
                jsonObject.put("acceptPrice", "");
            }

            if (rsMap.containsKey(regionId))
                jsonObject.put("supportName", rsMap.get(regionId).get("userName"));
            else
                jsonObject.put("supportName", "");

            if (trackMap.containsKey(customerId)) {
                String trackTime = trackMap.get(customerId).get("TRACK_TIME").toString();
                String visitContent = trackMap.get(customerId).get("VISIT_CONTENT").toString();
                jsonObject.put("TRACK_TIME", DateUtils.parse(trackTime, "MM/dd"));
                jsonObject.put("VISIT_CONTENT", visitContent);
            } else {
                jsonObject.put("TRACK_TIME", "");
                jsonObject.put("VISIT_CONTENT", "");
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", jsonObjectList);
        jsonObject.put("recordCount", cusCount);
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageCount", (int) Math.ceil(cusCount / 30.00));

        return jsonObject;
    }

    public JSONObject getById(String id) {
        JSONObject jsonObject = new JSONObject();
        JSONObject exihibitionCustomer = exhibitionCustomerInfoDao.getJSONById(id);
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isEmpty(id)) {
            condition.append(" AND EXHIBITION_INFO_ID=? ");
            sqlArgs.add(id);
        }
        List<JSONObject> intentionList = exhibitionIntentionDao.getJSONListByCondition(condition.toString(), sqlArgs.toArray());
        jsonObject.put("exihibitionCustomer", exihibitionCustomer);//展会客户
        jsonObject.put("intentionModelList", intentionList);//展会机型
//        jsonObject.put("customerInfo", wReportCustomerDao.getById(exihibitionCustomer.get("id").toString()));//客户基本信息
//        jsonObject.put("customerInfo", wReportCustomerDao.getById(exihibitionCustomer.get("id").toString()));//客户基本信息
        jsonObject.put("customerInfo", wReportCustomerDao.getById(exihibitionCustomer.get("customerId").toString()));//客户基本信息


        return jsonObject;
    }

    @Override
    public List<JSONObject> getTrackRecordList(String cusId) {
        List<JSONObject> jsonObjectList = exhibitionCustomerInfoDao.getTrackRecordList(cusId);

        for (JSONObject jsonObject : jsonObjectList) {
            String strDate = jsonObject.get("CREATE_TIME").toString();
            jsonObject.put("CREATE_TIME", DateUtils.parse(strDate, "yyyy/MM/dd"));
        }

        return jsonObjectList;
    }


    @Override
    public String saveExhibitionCustomerVisit(String jsonData) {
        ExhibitionCustomerInfoEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), ExhibitionCustomerInfoEntity.class);
        ExhibitionCustomerInfoEntity newEntity = JSON.toJavaObject(exhibitionCustomerInfoDao.getJSONById(entity.getId()), ExhibitionCustomerInfoEntity.class);
        newEntity.setTrackStatus(entity.getTrackStatus());
        if (entity.getTrackStatus().intValue() == 2) {
            newEntity.setDepositStatus(4);
        }
        WReportCusVisitEntity wReportCusVisitEntity = new WReportCusVisitEntity();
        wReportCusVisitEntity.setCustomerId(entity.getCustomerId());
        wReportCusVisitEntity.setVisitContent(entity.getVisitContent());
        wReportCusVisitDao.add(wReportCusVisitEntity);
        exhibitionCustomerInfoDao.update(newEntity);
        return entity.getId();
    }

    @Override
    public List<JSONObject> getSalerBySalerSupport(String userId, String userName) {
        List<JSONObject> jsonObjectList = exhibitionCustomerInfoDao.getSalerBySalerSupport(userId, userName);
        return jsonObjectList;
    }
}
